<?php


namespace App\Http\Services;


use App\DTO\FatBoard;
use App\Exceptions\ResourceNotFoundException;
use App\Models\Board;

class BoardService
{
    /**
     * @param string $title
     * @param int $userId
     * @return Board|\Illuminate\Database\Eloquent\Model
     */
    public function createBoard(string $title,int $userId)
    {
        $data = [
            'title' => $title,
            'user_id' => $userId
        ];
        return Board::create($data);
    }

    /**
     * @param int $userId
     * @param int|null $listId
     * @return array|mixed
     */
    public function getBoard(int $userId, int $listId = null)
    {
        if(!$listId) {
            $list =  Board::where(['user_id' => $userId])->get();
            return $list->map(function (Board $list) {
                return (new FatBoard($list))->getData();
            });
        } else {
            $list  = Board::where(['id' => $listId, 'user_id' => $userId])->get()->first()->toArray();
            return (new FatBoard($list))->getData();
        }
    }

    /**
     * @param int $listId
     * @return bool|null
     * @throws ResourceNotFoundException
     * @throws \Exception
     */
    public function deleteBoard(int $listId)
    {
        $list = Board::find($listId);
        if(!$list) {
            throw new ResourceNotFoundException();
        }
        return $list->delete();
    }

    /**
     * @param int $listId
     * @param array $options
     * @return Board|Board[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws ResourceNotFoundException
     */
    public function updateBoard(int $listId, array $options = [])
    {
        $list = Board::find($listId);
        if(!$list) {
            throw new ResourceNotFoundException();
        }
        if(!$list->update($options)) {
            throw new ResourceNotFoundException();
        }
        return $list;
    }
}